package http

import (
	"ce-cloud/pkg/log"
	"fmt"
	"github.com/gin-gonic/gin"
	"net"
)

var api *ApiServer

type ApiServer struct {
	engine *gin.Engine
}

func Start(ip string, port int) (*ApiServer, error) {
	api = new(ApiServer)
	gin.SetMode(gin.ReleaseMode)
	api.engine = gin.Default()
	//gin http路由
	router(api.engine)
	if ip == "0.0.0.0" {
		addr, err := net.InterfaceAddrs()
		if err != nil {
			log.Error("net.InterfaceAddrs() err:", err)
			return nil, err
		}
		fmt.Println("http swagger url:")
		for _, address := range addr {
			if ipNet, ok := address.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
				if ipNet.IP.To4() != nil {
					//fmt.Println(ipNet.IP.String())
					fmt.Printf("http://%s:%d/swagger/index.html#\n", ipNet.IP.String(), port)
				}
			}
		}
	} else {
		fmt.Printf("http swagger url: http://%s:%d/swagger/index.html#", ip, port)
	}
	err := api.engine.Run(fmt.Sprintf("%s:%d", ip, port))
	if err != nil {
		return nil, err
	}
	return api, nil
}

func (api *ApiServer) Close() {

}
